package com.ljd.sps;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;

public class SmallphoneScannerActivity extends Activity implements OnClickListener {
    public static final boolean LOG = true;

    private static final String TAG = "ljd";

    public static final String EXTRA_PHOTO_TYPE = "photo_type";

    public static final int _4X6 = 0;
    public static final int _3X5 = 1;
    public static final int _SLIDER = 2;
    public static final int _NEGATIVES = 3;

    private static final int MSG_SAVE_PHOTO = 0;
    private static final int MSG_EMAIL_PHOTO = 1;

    public static boolean isFinished = false;

    private static final String PHOTO_DIR = Environment.getExternalStorageDirectory() + "/DCIM/Camera";

    private static final String APP_ID = "400083866731885";

    private static final int REQUEST_CODE_GET_PHOTO_EMAIL = 666;
    private static final int REQUEST_CODE_GET_PHOTO_FACEBOOK = 777;

    private static final String[] PERMISSIONS = new String[] { "publish_stream", "read_stream", "offline_access",
            "user_photos" };

    private Facebook mFacebook;
    private AsyncFacebookRunner mAsyncRunner;

    private ProgressDialog mProgressDialog;
    private ImageView final_pic;

    private int mRequestCode;
    private Dialog dialog;

    private final class LoginDialogListener implements com.facebook.android.Facebook.DialogListener {

        public void onComplete(Bundle values) {
            // TODO Auto-generated method stub
            mProgressDialog = new ProgressDialog(SmallphoneScannerActivity.this);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();

            Bitmap bmp = ((BitmapDrawable) final_pic.getDrawable()).getBitmap();

            mAsyncRunner = new AsyncFacebookRunner(mFacebook);
            Bundle params = new Bundle();
            params.putString("message", "Uploaded on!!!!!!");
            params.putByteArray("picture", Util.Bitmap2Bytes(bmp)); //bytes contains photo bytes, no problem here
            mAsyncRunner.request("me/photos", params, "POST", new PostPhotoRequestListener(), null);
        }

        public void onFacebookError(FacebookError e) {
            if (LOG) {
                Log.d(TAG, e.getMessage());
            }
            Toast.makeText(SmallphoneScannerActivity.this, "Login onFacebookError", Toast.LENGTH_SHORT).show();
        }

        public void onError(DialogError e) {
            if (LOG) {
                Log.d(TAG, e.getMessage());
            }
            Toast.makeText(SmallphoneScannerActivity.this, "Login onError", Toast.LENGTH_SHORT).show();
        }

        public void onCancel() {
            // TODO Auto-generated method stub
            Toast.makeText(SmallphoneScannerActivity.this, "Login onCancel", Toast.LENGTH_SHORT).show();
        }

    }

    private final class PostPhotoRequestListener implements RequestListener {

        public void onComplete(String response, Object state) {
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
                mProgressDialog = null;
            }

            runOnUiThread(new Runnable() {

                public void run() {
                    Toast.makeText(SmallphoneScannerActivity.this, "Post photo successfully", Toast.LENGTH_SHORT)
                            .show();
                }
            });
        }

        public void onIOException(IOException e, Object state) {
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
                mProgressDialog = null;
            }

            runOnUiThread(new Runnable() {

                public void run() {
                    Toast.makeText(SmallphoneScannerActivity.this, "Post photo onIOException", Toast.LENGTH_SHORT)
                            .show();
                }
            });
        }

        public void onFileNotFoundException(FileNotFoundException e, Object state) {
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
                mProgressDialog = null;
            }

            runOnUiThread(new Runnable() {

                public void run() {
                    Toast.makeText(SmallphoneScannerActivity.this, "Post photo onFileNotFoundException",
                            Toast.LENGTH_SHORT).show();
                }
            });
        }

        public void onMalformedURLException(MalformedURLException e, Object state) {
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
                mProgressDialog = null;
            }

            runOnUiThread(new Runnable() {

                public void run() {
                    Toast.makeText(SmallphoneScannerActivity.this, "Post photo onMalformedURLException",
                            Toast.LENGTH_SHORT).show();
                }
            });
        }

        public void onFacebookError(FacebookError e, Object state) {
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
                mProgressDialog = null;
            }

            runOnUiThread(new Runnable() {

                public void run() {
                    Toast.makeText(SmallphoneScannerActivity.this, "Post photo onFacebookError", Toast.LENGTH_SHORT)
                            .show();
                }
            });
        }

    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (mProgressDialog != null) {
                mProgressDialog.dismiss();
                mProgressDialog = null;
            }

            String photoFileName = (String) msg.obj;
            Toast.makeText(SmallphoneScannerActivity.this, "Save as " + PHOTO_DIR + "/" + photoFileName,
                    Toast.LENGTH_LONG).show();

            switch (msg.what) {
            case MSG_EMAIL_PHOTO:
                File oFile = new File(PHOTO_DIR + File.separator + photoFileName);
                emailPhoto(Uri.fromFile(oFile));
                break;
            }
        }

    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.smallphonescanner);

        findViewById(R.id.btn_4x6).setOnClickListener(this);
        findViewById(R.id.btn_3x5).setOnClickListener(this);
        findViewById(R.id.slides).setOnClickListener(this);
        findViewById(R.id.negatives).setOnClickListener(this);
        findViewById(R.id.save).setOnClickListener(this);
        findViewById(R.id.email).setOnClickListener(this);
        findViewById(R.id.help).setOnClickListener(this);
        findViewById(R.id.facebook).setOnClickListener(this);
        findViewById(R.id.delete).setOnClickListener(this);
        findViewById(R.id.btn_panel_cancel).setOnClickListener(this);
        findViewById(R.id.btn_panel_photo).setOnClickListener(this);
        findViewById(R.id.btn_panel_local).setOnClickListener(this);

        new Handler() {

            @Override
            public void handleMessage(Message msg) {
                // TODO Auto-generated method stub
                findViewById(R.id.splash).setVisibility(View.GONE);
            }

        }.sendEmptyMessageDelayed(0, 1500);

        final_pic = (ImageView) findViewById(R.id.final_pic);
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btn_4x6:
            Intent intent = new Intent(this, TakePhotoActivity.class);
            intent.putExtra(EXTRA_PHOTO_TYPE, _4X6);
            startActivity(intent);
            break;
        case R.id.btn_3x5:
            intent = new Intent(this, TakePhotoActivity.class);
            intent.putExtra(EXTRA_PHOTO_TYPE, _3X5);
            startActivity(intent);
            break;
        case R.id.slides:
            intent = new Intent(this, TakePhotoActivity.class);
            intent.putExtra(EXTRA_PHOTO_TYPE, _SLIDER);
            startActivity(intent);
            break;
        case R.id.negatives:
            intent = new Intent(this, TakePhotoActivity.class);
            intent.putExtra(EXTRA_PHOTO_TYPE, _NEGATIVES);
            startActivity(intent);
            break;
        case R.id.save:
            if (final_pic.getVisibility() == View.VISIBLE) {

                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setCancelable(false);
                mProgressDialog.show();

                new Thread() {

                    public void run() {
                        String photoFileName = savePhoto();
                        Message msg = mHandler.obtainMessage(MSG_SAVE_PHOTO);
                        msg.obj = photoFileName;
                        mHandler.sendMessage(msg);
                    }
                }.start();
            }
            break;
        case R.id.email:
            if (final_pic.getVisibility() == View.VISIBLE) {
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setCancelable(false);
                mProgressDialog.show();

                new Thread() {

                    public void run() {
                        String photoFileName = savePhoto();
                        Message msg = mHandler.obtainMessage(MSG_EMAIL_PHOTO);
                        msg.obj = photoFileName;
                        mHandler.sendMessage(msg);
                    }
                }.start();
            } else {
                showBtnPanel(REQUEST_CODE_GET_PHOTO_EMAIL);
            }
            break;
        case R.id.help:
            startActivity(new Intent(this, HelpActivity.class));
            break;
        case R.id.facebook:
            if (final_pic.getVisibility() == View.VISIBLE) {
                loginFacebook();
            } else {
                showBtnPanel(REQUEST_CODE_GET_PHOTO_FACEBOOK);
            }
            break;
        case R.id.delete:
            clearTempPhoto();
            break;
        case R.id.btn_panel_cancel:
            hideBtnPanel();
            break;
        case R.id.btn_panel_local:
            Intent innerIntent = new Intent(Intent.ACTION_PICK);
            innerIntent.setType("image/*");
            startActivityForResult(innerIntent, mRequestCode);
            hideBtnPanel();
            break;
        case R.id.btn_panel_photo:
            showDialog(0);
            hideBtnPanel();
            break;
        case R.id.ok:
            dialog.cancel();
            break;
        }
    }

    public void onResume() {
        super.onResume();
        if (isFinished) {
            final_pic.setVisibility(View.VISIBLE);
            int size = 1024 * 1024;
            Bitmap bmp = Util.loadBitmapWithSizeLimitation(this, size, "dest.jpg", getFilesDir().getAbsolutePath());

            if (bmp != null) {
                //	    		int degree = ImageUtil.getImageRotateDegree(getFilesDir() + "/dest.jpg");
                //	        	if(degree != 0){
                //	                Matrix mat = new Matrix();
                //	                mat.postRotate(degree);
                //	                bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mat, true);     
                //	            }
                final_pic.setImageBitmap(bmp);
                ImageView del = (ImageView) findViewById(R.id.delete);
                del.setVisibility(View.VISIBLE);
            } else {
                final_pic.setVisibility(View.GONE);
                findViewById(R.id.delete).setVisibility(View.GONE);
            }
        } else {
            final_pic.setVisibility(View.GONE);
            findViewById(R.id.delete).setVisibility(View.GONE);
        }
    }

    public void onDestroy() {
        super.onDestroy();
        //		saveLocation();
        clearTempPhoto();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (LOG) {
            Log.i(TAG, "onActivityResult" + requestCode + "|" + resultCode);
        }

        if (resultCode != RESULT_OK) {
            return;
        }

        Uri photo_uri = null;
        if (data != null && data.getData() != null) {
            photo_uri = data.getData();
        }

        switch (requestCode) {
        case REQUEST_CODE_GET_PHOTO_EMAIL:
            if (photo_uri != null) {
                emailPhoto(photo_uri);
            }
            break;
        case REQUEST_CODE_GET_PHOTO_FACEBOOK:
            if (photo_uri != null) {
                Bitmap bmp = Util.loadBitmapWithSizeLimitation(this, 1024 * 1024, photo_uri);
                if (bmp != null) {
                    final_pic.setImageBitmap(bmp);
                }
                loginFacebook();
            }
            break;
        default:
            if (mFacebook != null) {
                mFacebook.authorizeCallback(requestCode, resultCode, data);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:
            if (findViewById(R.id.btn_panel).getVisibility() == View.VISIBLE) {
                hideBtnPanel();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        // TODO Auto-generated method stub
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.dialogmain, null);
        view.findViewById(R.id.ok).setOnClickListener(this);
        dialog = new Dialog(this, R.style.dialog);
        dialog.setContentView(view);
        return dialog;
    }

    private void clearTempPhoto() {
        File file = new File(getFilesDir() + "/src.jpg");
        if (file.exists()) {
            file.delete();
        }

        file = new File(getFilesDir() + "/dest.jpg");
        if (file.exists()) {
            file.delete();
        }

        findViewById(R.id.delete).setVisibility(View.GONE);
        final_pic.setVisibility(View.GONE);
        BitmapDrawable d = ((BitmapDrawable) final_pic.getDrawable());
        if (d != null) {
            Bitmap b = d.getBitmap();
            if (b != null) {
                b.recycle();
            }
        }
        final_pic.setImageBitmap(null);

        System.gc();
    }

    private String savePhoto() {

        String photoFileName = getPhotoFileName();
        new File(PHOTO_DIR).mkdirs();

        File oFile = new File(PHOTO_DIR + File.separator + photoFileName);
        File iFile = new File(getFilesDir() + File.separator + "dest.jpg");
        FileOutputStream out;
        FileInputStream in;
        try {
            oFile.createNewFile();
            out = new FileOutputStream(oFile);
            in = new FileInputStream(iFile);
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            out.flush();

            in.close();
            out.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return photoFileName;

    }

    private void emailPhoto(Uri uri) {
        //		File file = new File(getFilesDir() + "/dest.jpg"); //附件文件地址
        //		if (LOG) {
        //			if (file.exists()) {
        //				Log.d(TAG, "photo is exit:"+Uri.fromFile(file));
        //			}
        //		}
        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.setType("image/jpeg");
        sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
        startActivity(Intent.createChooser(sendIntent, "Send Image To:"));
    }

    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }

    private void loginFacebook() {
        mFacebook = new Facebook(APP_ID);

        if (!mFacebook.isSessionValid()) {
            Toast.makeText(SmallphoneScannerActivity.this, "Facebook is not valid", Toast.LENGTH_SHORT).show();

            mFacebook.authorize(this, PERMISSIONS, new LoginDialogListener());
        } else {
            Toast.makeText(SmallphoneScannerActivity.this, "Facebook is valid", Toast.LENGTH_SHORT).show();

            mProgressDialog = new ProgressDialog(SmallphoneScannerActivity.this);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();

            Bitmap bmp = ((BitmapDrawable) final_pic.getDrawable()).getBitmap();

            mAsyncRunner = new AsyncFacebookRunner(mFacebook);
            Bundle params = new Bundle();
            params.putString("message", "Uploaded on!!!!!!");
            params.putByteArray("picture", Util.Bitmap2Bytes(bmp)); //bytes contains photo bytes, no problem here
            mAsyncRunner.request("me/photos", params, "POST", new PostPhotoRequestListener(), null);
        }
    }

    private void showBtnPanel(int requestCode) {
        mRequestCode = requestCode;
        findViewById(R.id.btn_panel).setVisibility(View.VISIBLE);
    }

    private void hideBtnPanel() {
        mRequestCode = 0;
        findViewById(R.id.btn_panel).setVisibility(View.GONE);
    }

    //	private void saveLocation() {
    //		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    //		File file = new File(PHOTO_DIR+"/location.txt");
    //		BufferedWriter bw = null;
    //		try {
    //			bw = new BufferedWriter(new FileWriter(file));
    //			
    //			RectF rect = Util.getLastChooseArea(sp, _NEGATIVES);
    //			if (rect != null) {
    //				bw.write("Negatives:"+rect.left+"|"+rect.top+"|"+rect.right+"|"+rect.bottom);
    //				bw.write("\n");
    //			}
    //
    //			rect = Util.getLastChooseArea(sp, _SLIDER);
    //			if (rect != null) {
    //				bw.write("Slider:"+rect.left+"|"+rect.top+"|"+rect.right+"|"+rect.bottom);
    //				bw.write("\n");
    //			}
    //
    //			rect = Util.getLastChooseArea(sp, _3X5);
    //			if (rect != null) {
    //				bw.write("3x5:"+rect.left+"|"+rect.top+"|"+rect.right+"|"+rect.bottom);
    //				bw.write("\n");
    //			}
    //
    //			rect = Util.getLastChooseArea(sp, _4X6);
    //			if (rect != null) {
    //				bw.write("4x6:"+rect.left+"|"+rect.top+"|"+rect.right+"|"+rect.bottom);
    //				bw.write("\n");
    //			}
    //			
    //			bw.flush();
    //		} catch (FileNotFoundException e) {
    //			// TODO Auto-generated catch block
    //			e.printStackTrace();
    //		} catch (IOException e) {
    //			// TODO Auto-generated catch block
    //			e.printStackTrace();
    //		} finally {
    //			try {
    //				if (bw != null) {
    //					bw.close();
    //				}
    //			} catch (IOException e) {
    //				// TODO Auto-generated catch block
    //				e.printStackTrace();
    //			}
    //		}
    //	}
}